 /**
 * Description: 内部资料
 * @author:jacky
 * @since:1.0.0
 *
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2018-06-11   jacky       1.0.0     Initial
 */
package com.metro.demo.material.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.github.pagehelper.PageInfo;
import com.metro.core.annotation.BusinessDesc;
import com.metro.core.page.Page;
import com.metro.core.vo.JsonResult;
import com.metro.core.vo.QueryParams;
import com.metro.core.vo.ResultCode;
import com.metro.core.vo.inf.IResult;
import com.metro.demo.common.beans.constant.PropertiesEnum;
import com.metro.demo.common.beans.vo.WebUserInfo;
import com.metro.demo.material.beans.vo.BizInsideMaterial;
import com.metro.demo.material.service.inf.IBizInsideMaterialService;
import com.metro.demo.web.controller.BaseController;
 /**
 * 内部资料<br>
 *
 * @author:jacky
 * @since:1.0.0
 * @version [1.0.0, 2018-06-11]
 */
@Controller
@RequestMapping("/bizInsideMaterial")
public class BizInsideMaterialController extends BaseController {
    //菜单编码
    private static final String menuCode = "BIZ_INSIDE_MATERIAL";
    //模块描述
    private static final String MODULE_DESC = "内部资料";
    @Autowired
    private IBizInsideMaterialService bizinsidematerialService;
    @Override
    protected String getViewDir() {
        return "material/";
    }
    
    /**
     * 去查询内部资料
     * 
     * @param bizinsidematerial 内部资料页面表单对象
     * @param page 分页配置
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-06-11]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "查询内部资料列表")
    @RequiresPermissions(menuCode + ":view")
    @SuppressWarnings("all")
    @RequestMapping(value = "list", method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView list(BizInsideMaterial bizinsidematerial) {
        ModelAndView mav = new ModelAndView();
        //获取用户的登录信息
    	Subject currentUser = SecurityUtils.getSubject();
        WebUserInfo userInfo  = (WebUserInfo)currentUser.getPrincipal();
        //获取登录用户名
        String username = userInfo.getUserName();
        try {
            mav.setViewName(getView("bizinsidematerial_list"));
            mav.addObject("searchEntity", bizinsidematerial);
            mav.addObject("username", username);
        } catch (Exception ex) {
            log.error("查询内部资料出错", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }

    /**
     * 查询内部资料
     *
     * @param bizinsidematerial 内部资料页面表单对象
     * @param page 分页配置
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-06-11]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "查询内部资料列表")
    @RequiresPermissions(menuCode + ":view")
    @SuppressWarnings("all")
    @RequestMapping(value = "dolist", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JsonResult dolist(BizInsideMaterial bizinsidematerial, Page page, QueryParams<BizInsideMaterial> queryParams) {
        JsonResult jr = new JsonResult();
        try {
            queryParams.setPaging(page);
            queryParams.setEntity(bizinsidematerial);
            PageInfo<BizInsideMaterial> pageInfo = bizinsidematerialService.queryForPage(queryParams);
            jr.setData(pageInfo);
            jr.setResult(ResultCode.SUCCESS);
        } catch (Exception ex){
            log.error("查询内部资料出错",ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

    /**
     * 去新增内部资料
     * 
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-06-11]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去新增内部资料")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "create")
    public ModelAndView createForm(Model model, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        try {
        	mav.setViewName(getView("insidefileInput"));
        } catch (Exception ex) {
            log.error("去新增内部资料出错", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }
    
    /**
     * 初始化新增修改内部资料所需参数
     * @author jacky
     */
    private void initCreateOrUpdateFrom(ModelAndView mav, String action){
        mav.addObject("action", action);
        mav.setViewName(getView("bizinsidematerial_form"));
    }
    
    /**
     * 新增内部资料
     * 
     * @param entity 内部资料页面表单对象
     * @param request 请求对象
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-06-11]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "新增内部资料")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "save", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult saveBizInsideMaterial(BizInsideMaterial entity, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        try {
            IResult res = bizinsidematerialService.save(entity);
            jr.setResult(res);
            log.debug("新增内部资料成功【{}】", entity);
        } catch (Exception ex) {
            log.error("新增内部资料出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

    /**
     * 删除内部资料
     * 
     * @param id 内部资料页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-06-11]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "删除内部资料")
    @RequiresPermissions(menuCode + ":delete")
    @RequestMapping(value = "delete", method = { RequestMethod.POST })
    @ResponseBody
    public JsonResult delete(String id, HttpServletRequest request){
        JsonResult jr = new JsonResult();
        try {
            log.debug("删除内部资料id={}",id);
            IResult codeMsg = bizinsidematerialService.deleteFileById(id);
            jr.setResult(codeMsg);
        } catch (Exception ex) {
            log.error("删除内部资料出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    
    /**
     * 去修改内部资料
     * 
     * @param id 内部资料页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-06-11]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去修改内部资料")
    @RequiresPermissions(menuCode + ":edit")
    @RequestMapping(value = "edit/{id}", method = { RequestMethod.GET})
    public ModelAndView updateForm(@PathVariable Long id, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        try {
            BizInsideMaterial entity = bizinsidematerialService.getById(id);
            mav.addObject("entity", entity);
            initCreateOrUpdateFrom(mav,"edit");
        } catch (Exception ex) {
            log.error("去修改内部资料", ex);
            mav.setView(new RedirectView("list"));
        }
        return mav;
    }

    /**
     * 修改内部资料
     * 
     * @param entity 内部资料页面表单对象
     * @param request 请求对象
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-06-11]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "修改内部资料")
    @RequiresPermissions(menuCode + ":edit")
    @RequestMapping(value = "update", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult updateBizInsideMaterial(BizInsideMaterial entity, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        try {
            IResult res = bizinsidematerialService.update(entity);
            jr.setResult(res);
            log.debug("修改内部资料成功【{}】", entity);
        } catch (Exception ex) {
            log.error("修改内部资料出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }
    
    /**
     * 去查看内部资料
     * 
     * @param id 内部资料页面表单对象唯一标识
     * @return 结果视图
     * @author jacky
     * @since [1.0.0]
     * @version [1.0.0, 2018-06-11]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去查看内部资料详情")
    @RequiresPermissions(menuCode + ":view")
    @RequestMapping(value = "info/{id}", method = { RequestMethod.GET })
    public ModelAndView info(@PathVariable Long id) {
        ModelAndView mav= new ModelAndView();
        try {
            mav.addObject("entity", bizinsidematerialService.getById(id));
            mav.setViewName(getView("bizinsidematerial_info"));
        } catch (Exception ex) {
            log.error("查看内部资料出错", ex);
        }
        return mav;
        
    }
    
    /**
     * 文件上传
     * @param files
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadMultiple", method = RequestMethod.POST, produces = "application/json;charset=utf8")
    @ResponseBody
    public JsonResult uploadMultipleFileHandler(@RequestParam("file") MultipartFile[] files,HttpServletRequest request) throws IOException {
    	JsonResult jr = new JsonResult();
    	ArrayList<Integer> arr = new ArrayList<>();
    	//获取用户的登录信息
    	Subject currentUser = SecurityUtils.getSubject();
        WebUserInfo userInfo  = (WebUserInfo)currentUser.getPrincipal();
        //获取登录用户名
        String username = userInfo.getUserName();
        //获取当前时间
        String time= new java.text.SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
        //遍历接收到的文件
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i]; 
            //获取文件名
            String fileName = file.getOriginalFilename();
            //本地存储的文件名
            String name = time+ "-" + fileName;
            //获取系统文件上传根路径
            String dir = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT)+"/implMaterial/insideMaterial/";
            //如果路径不存在 则新建
            File rootFile = new File(dir);
            if(!rootFile.exists()){  
            	rootFile.mkdirs();  
            }
            
            if (!file.isEmpty()) {
                InputStream in = null;
                OutputStream out = null;
                try {
                    String path = dir +"/"+ name; 
                    File serverFile = new File(path);
                    in = file.getInputStream();
                    out = new FileOutputStream(serverFile);
                    byte[] b = new byte[1024];
                    int len = 0;
                    while ((len = in.read(b)) > 0) {
                        out.write(b, 0, len);
                    }
                    out.close();
                    in.close();
                    //设置存入数据库的路径
                    String savePath = "/implMaterial/insideMaterial/"+ name;
                    //经销商号码、名称、路径保存到数据库
                    BizInsideMaterial entity = new BizInsideMaterial();
                    entity.setUploadPerson(username);
                    entity.setMaterialName(fileName);
                    entity.setType("1");
                    entity.setPath(savePath);
                    //保存文件路径到数据库
                   IResult res = bizinsidematerialService.save(entity);
                    jr.setResult(res);
                } catch (Exception e) {
                    arr.add(i);
                } finally {
                    if (out != null) {
                        out.close();
                        out = null;
                    }

                    if (in != null) {
                        in.close();
                        in = null;
                    }
                }
            } else {
                arr.add(i);
            }
        }
        return jr;
    }
    
    /**
     * 下载
     * @param code
     * @param type
     * @param entity
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value="/download/{id}")
    public void doGet(@PathVariable String id,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    	BizInsideMaterial entity = new BizInsideMaterial();
    	entity =  bizinsidematerialService.getById(Long.valueOf(id));
        //下载文件路径
        String path = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT) + entity.getPath();
        File file = new File(path);
        // 取得文件名。
        String filename = file.getName();
    	// 2.通知浏览器以下载方式打开  
    	// 如果文件名中包含中文，则文件名要进行URL编码，URLEncoding.encode;如果不进行编码则文件名显示错误并且不可下载。  
    	response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));  
    	// 3.向浏览器写出数据  
    	FileInputStream in = null;  
    		try {  
    				OutputStream out = response.getOutputStream();  
    				in = new FileInputStream(path);  
    				byte buffer[] = new byte[1024];  
    				int len = 0;  
    		while ((len = in.read(buffer)) > 0) {  
    				out.write(buffer, 0, len);  
    		}  
    	} finally {  
    		if (in != null) {  
    			in.close(); // 关闭流  
    	     }  
    	}  
   }  
}
